document.addEventListener('DOMContentLoaded', function () {
  const resumeData = JSON.parse(localStorage.getItem('resumeData'));
  console.log(resumeData)
  const formContainer = document.querySelector('.form-container');
  const btnContainer = document.getElementById('button-container');
  const field = document.getElementById('field');

  if (resumeData) {
    try {
      const content = resumeData.content;
      if (typeof content === 'string' && (content.startsWith('http://') || content.startsWith('https://'))) {
        if (formContainer) {
          formContainer.style.display = 'none';
        }
        if (field) {
          field.innerHTML = '';
          const combinedContainer = document.createElement('div');
          combinedContainer.className = 'download-link-container';
          const linkContainer = document.createElement('div');
          linkContainer.className = 'resume-link';

          const link = document.createElement('a');
          link.href = content;
          link.textContent = '点击下载简历';
          link.target = '_blank';
          link.className = 'download-link';

          linkContainer.appendChild(link);
          combinedContainer.appendChild(linkContainer);
          if (btnContainer) {
            btnContainer.parentNode.removeChild(btnContainer);
            combinedContainer.appendChild(btnContainer);
          }
          field.appendChild(combinedContainer);
        }
      } else {
        const contentObj = JSON.parse(content);
        const form = document.getElementById('userForm');
        if (form) {
          for (const key in contentObj) {
            const input = form.querySelector(`[name="${key}"]`);
            if (input) {
              if (input.type === 'radio') {
                const radio = form.querySelector(`[name="${key}"][value="${contentObj[key]}"]`);
                if (radio) radio.checked = true;
              } else if (input.tagName === 'SELECT') {
                const option = input.querySelector(`option[value="${contentObj[key]}"]`);
                if (option) option.selected = true;
              } else {
                input.value = contentObj[key];
              }
              input.readOnly = true;
              input.style.border = '1px solid #ccc';
              input.style.padding = '5px';
            }
          }
        }
      }
    } catch (error) {
      console.error('解析简历数据时出错:', error);
      alert('解析简历数据时出错，请检查数据格式');
    }
  }
});

var resumeData = JSON.parse(localStorage.getItem('resumeData'));
var editResumeBtn = document.getElementById('editResumeBtn');
var deleteResumeBtn = document.getElementById('deleteResumeBtn');
var updateResumeBtn = document.getElementById('updateResume');
function deleteResume() {
  const usersId = localStorage.getItem('userId');
  if (!usersId) {
    alert('未获取到简历ID，请重新登录或检查数据');
    return;
  }
  if (confirm('确定要删除这份简历吗？')) {
    const resumeData = JSON.parse(localStorage.getItem('resumeData'));
    const id = resumeData ? resumeData.id : null;
    if (!id) {
      alert('未获取到简历ID，请重新登录或检查数据');
      return;
    }
    const url = `http://192.168.244.14:8080/resumeStatus/delete/${id}&${usersId}`;

    fetch(url, {
      method: 'DELETE'
    })
      .then(response => {
        if (!response.ok) {
          throw new Error('网络响应错误：' + response.status);
        }
        return response.json();
      })
      .then(data => {
        if (data && data.code === 1) {
          alert('简历删除成功');
          window.location.href = "http://127.0.0.1:5501/sparkResume/html/users-function1.html";
        } else {
          alert('删除失败：' + (data && data.msg ? data.msg : '未知错误'));
        }
      })
      .catch(error => {
        console.error('删除请求出错:', error);
        alert('删除请求出错，请检查网络连接');
      });
  }
}

document.addEventListener('DOMContentLoaded', function () {
  const deleteResumeBtn = document.getElementById('deleteResumeBtn');
  if (deleteResumeBtn) {
    deleteResumeBtn.addEventListener('click', deleteResume);
  }
});


document.addEventListener('DOMContentLoaded', function () {
  const editResumeBtn = document.getElementById('editResumeBtn');
  if (editResumeBtn) {
    editResumeBtn.addEventListener('click', function () {
      const userId = localStorage.getItem('userId');
      if (!userId) {
        alert('未获取到用户 ID，请先登录');
        return;
      }
      fetch(`http://192.168.244.14:8080/resumeStatus/view/${userId}`)
        .then(response => {
          if (!response.ok) {
            throw new Error('网络响应错误：' + response.status);
          }
          return response.json();
        })
        .then(data => {
          console.log('后端返回的简历信息:', data);
          if (data && data.code === 1) {
            localStorage.setItem('resumeData', JSON.stringify(data.data));
            window.location.href = "http://127.0.0.1:5501/sparkResume/html/editResume.html";
          } else {
            alert('获取简历信息失败：' + (data && data.msg ? data.msg : '未知错误'));
          }
        })
        .catch(error => {
          console.error('获取简历信息请求出错:', error);
        });
    });
  }
});

document.addEventListener('DOMContentLoaded', function () {
  const checkCommentBtn = document.getElementById('checkComment');
  if (checkCommentBtn) {
    checkCommentBtn.addEventListener('click', function () {
      const resumeData = JSON.parse(localStorage.getItem('resumeData'));
      const userId = resumeData ? resumeData.usersId : null;
      if (!userId) {
        alert('未获取到用户ID，请重新查看简历');
        return;
      }

      const url = `http://192.168.244.14:8080/comment/select/${userId}`;
      fetch(url, {
        method: 'GET',
        headers: {
          'Accept': 'application/json'
        }
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('网络响应错误：' + response.status);
          }
          return response.json();
        })
        .then(data => {
          console.log('后端返回的留言数据:', data);
          if (data && data.code === 1) {
            const comment = data.data.comment;
            if (comment) {
              alert(`${comment}`);
            } else {
              alert('管理员还未留言，请稍等哦~~~');
            }
          } else {
            alert('查询留言失败：' + (data && data.msg ? data.msg : '未知错误'));
          }
        })
        .catch(error => {
          console.error('查询留言请求出错:', error);
          alert('查询留言请求出错，请检查网络连接');
        });
    });
  }
});
updateResumeBtn.addEventListener('click', function () {
  event.preventDefault();
  const form = document.getElementById('userForm');
  const formData = new FormData(form);
  const resumeData = {};
  formData.forEach(function (value, key) {
    resumeData[key] = value;
  });
  const usersId = localStorage.getItem('userId');
  if (!usersId) {
    alert('未获取到用户ID，请重新登录或检查数据');
    return;
  }
  const content = JSON.stringify(resumeData);
  fetch(`http://192.168.244.14:8080/resumeStatus/update/${usersId}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ content, id: parseInt(usersId), updater: parseInt(usersId) })
  })
    .then(response => {
      if (!response.ok) {
        throw new Error('网络响应错误：' + response.status);
      }
      return response.json();
    })
    .then(data => {
      console.log('后端返回的数据:', data);
      if (data && data.code === 1) {
        alert('简历修改成功');
        window.location.href = "http://127.0.0.1:5501/sparkResume/html/users-function1.html";
      } else {
        alert('简历修改失败：' + (data && data.msg ? data.msg : '未知错误'));
      }
    })
    .catch(error => {
      console.error('修改简历请求出错:', error);
    });
});



